class Solution:
    def longestValidParentheses(self, s: str) -> int:
        n = len(s)
        if n == 0: 
            return 0
        stack = []
        max_length = 0
        for i in range(n):
            if s[i] == '(' or not stack or s[stack[-1]] == ')':
                stack.append(i)
            else:
                stack.pop()
                max_length = max(max_length, i - (stack[-1] if stack else -1))
        return max_length